import React from 'react';
import { List, InputItem, WhiteSpace, Button, Picker, DatePicker, WingBlank, Toast, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import qs from 'query-string';
import { routerRedux } from 'dva/router';
import Container from '../components/Base/Container';
import Coming from './Coming';
import VerifyCodeItem from '../components/Base/VerifyCodeItem';
import { fetchPaidVip } from '../services/vipService';

let map;
// let zoom=10;  //地图放大等级
let defaultDistance=99999999999999999999999999999999999999999999999;

class RegPage extends React.Component {

  state={
    currentLocation:[],
    showNum:5,
    change_branch_no:'',
  }

  submit = () => {
    this.props.form.validateFields((error, value) => {
      if (error) {
        Toast.fail(_.map(error, (v) => {
          return _.get(v, 'errors[0].message');
        })[0], 1);
        return;
      }

      const { saleman_id } = this.props.location.query;
      const branch_no = this.getBranchNo();

      if(!branch_no){
        if(!this.state.change_branch_no.length){
          Toast.fail('请选择门店', 1);
          return;
        }
      }

      if (value.mobile) {
        value.mobile = value.mobile.replace(/\s/ig, '');
      }
      if (value.vip_sex) {
        value.vip_sex = value.vip_sex[0];
      }
      if (value.birthday) {
        value.birthday = value.birthday.startOf('day');
      }
      value.shopId = this.props.location.query.shopId;
      if (branch_no) {
        value.branchId = branch_no;
      }
      else if (this.state.change_branch_no) {
        value.branchId = this.state.change_branch_no;
      }
      const result = _.pickBy(_.assign({}, value, {
        saleman_id,
      }), v => !_.isNil(v) && !_.isEmpty(v));
      this.props.save(result);
    });
  };
  getBranchNo = () => {
    let branch_no = this.props.location.query.branch_no;
    return branch_no ? branch_no.split(',')[0] : null;
  };
  renderBranchSelect = () => {
    if (this.getBranchNo()) {
      return null;
    }
    return(
      <div>
        <div style={{margin:'0 0.3rem', lineHeight:'0.88rem', fontSize:'0.34rem'}}>选择门店</div>

        { this.branchList() }

        {
          this.state.showNum<this.props.branchList.length?
            <div onClick={()=>{
              this.setState((prevState, props)=>({
                showNum:prevState.showNum+5,
              }))
            }} style={{textAlign:'center', lineHeight:'3em'}}>继续显示5个</div>
            :''
        }
      </div>
    )
  };

  branchList=()=>{
    let list=[];
    this.props.branchList.map(item=>{
      let obj=Object.assign({}, item);

      let pointA = new BMap.Point(this.state.currentLocation[0], this.state.currentLocation[1]);
      if(item.location){
        let pointB = new BMap.Point(item.location['0'], item.location['1']);
        obj.distance=(map.getDistance(pointA,pointB)).toFixed(2);  //米
      }
      else{
        obj.distance=defaultDistance;
      }
      list.push(obj);
    })

    list=list.sort((item1, item2)=>{
      return item1.distance-item2.distance;
    })

    let arr=list.map(item=>(
      <div onClick={()=>{
        this.setState({
          change_branch_no:item.branch_no,
        })
      }} key={item.branch_no} style={{backgroundColor:this.state.change_branch_no===item.branch_no?'rgb(79,161,197)':'', margin:'0.5em 0.3rem 0 0.3rem', padding:'0.5em 0'}}>
        <div style={{fontSize:'0.4rem', marginBottom:'0.2em'}}>{item.branch_name}</div>
        <div style={{display:'flex'}}>
            <div style={{flex:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{item.distance!==defaultDistance?item.qez_address:'待门店补充'}</div>
            <div style={{width:'2rem', textAlign:'right'}}>{this.state.currentLocation.length?(item.distance!==defaultDistance?(item.distance<1000?`${item.distance}m`:`${(item.distance/1000).toFixed(2)}km`):''):''}</div>
          </div>
      </div>
    ))
    return arr.slice(0,this.state.showNum);
  }

  componentWillMount() {
    const { location: { query: { shopId, branch_no, saleman_id } } } = this.props;
    fetchPaidVip(shopId).then((res) => {
      Toast.loading('请稍候...');
      if (res.data && res.data.length) {
        const paidVip = res.data[0];
        if (paidVip && paidVip.enable) {
          const params = qs.stringify(_.pickBy({
            shopId,
            regBranchNo: branch_no,
            regSalemanId: saleman_id,
            localRoute: 'reg',
          }, v => !_.isNil(v)));
          window.location.href = `http://${window.location.host}/#/third_vipCard?${params}`;
        }
      }
    });
  }

  componentDidMount() {
    this.props.fetchBranchList();

    if(this.getBranchNo()){
      return
    }

    map = new BMap.Map("allmap", {enableMapClick:false});

    let geolocation = new BMap.Geolocation();
    let _this=this;
    geolocation.getCurrentPosition(function(r){
      if(this.getStatus() == BMAP_STATUS_SUCCESS){
        if(!r.accuracy){
          return
        }

        _this.setState({
          currentLocation:[r.point.lng, r.point.lat],
        })
      }
      else {
        Toast.fail('failed'+this.getStatus(), 1);
      }
    },{enableHighAccuracy: true});

  }


  render() {
    const { getFieldProps } = this.props.form;
    return (
      <Container title="会员注册" navOption={{ iconName: null }}>
        <div style={{ backgroundColor:'white' }}>
          <WhiteSpace/>
          <List>
            <InputItem
              {...getFieldProps('mobile', {
                rules: [{ required: true, message: '请输入手机号' }],
              })}
              type="phone"
              placeholder=""
            >手机号码</InputItem>

            <VerifyCodeItem
              codeType="4"
              fieldName="verifyCode"
              phoneField="mobile"
              shopId={this.props.location.query.shopId}
              form={this.props.form}
            />

            <InputItem
              {...getFieldProps('vip_name', {
                rules: [{ required: true, message: '请输入会员姓名' }, { max: 8, message: '姓名长度不能超过8位' }],
              })}
              type="string"
              placeholder=""
            >会员姓名</InputItem>
            <Picker
              data={[
                {
                  label: '男',
                  value: '男',
                },
                {
                  label: '女',
                  value: '女',
                }]}
              cols={1}
              {...getFieldProps('vip_sex', {
                rules: [{ required: true, message: '请选择宝宝性别' }],
              })}
            >
              <List.Item arrow="horizontal">宝宝性别</List.Item>
            </Picker>
            <DatePicker
              mode="date"
              title="选择宝宝生日"
              maxDate={moment().add(2, 'years')}
              minDate={moment().subtract(12, 'years')}
              {...getFieldProps('birthday', {
                rules: [{ required: true, message: '请选择宝宝生日' }],
              })}
            >
              <List.Item arrow="horizontal">宝宝生日</List.Item>
            </DatePicker>
            <TextareaItem
              title="家庭地址"
              autoHeight
              {...getFieldProps('vip_add', {
                rules: [{ max: 80, message: '地址长度不能超过80位' }],
              })}
            />
            {this.renderBranchSelect()}
          </List>
          <WhiteSpace size="xl"/>
          <WingBlank>
            <Button type="primary" onClick={this.submit} >确定</Button>
          </WingBlank>
          <WhiteSpace size="xl"/>
        </div>
      </Container>
    );
  }
}

export default connect((state) => {
  return {
    branchList: state.stat.branchList,
  };
}, (dispatch, props) => {
  return {
    fetchBranchList: () => {
      dispatch({
        type: 'stat/fetchBranchList',
        payload: { shopId: props.location.query.shopId, showAll: true },
      });
    },
    save: (value) => {
      value = value || {};
      value.noBindCard = true;
      dispatch({
        type: 'vip/reg',
        payload: value,
      });
    },
  };
})(createForm()(RegPage));

